package com.bt7274.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bt7274.mapper.PeerMapper;
import com.bt7274.pojo.Peer;
import com.bt7274.service.PeerService;
import jakarta.annotation.Resource;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Locale;

/**
 * @Data 2025/5/28 11:51
 * @Author hp
 * @Version 1.0
 * @Description PeerServiceImpl
 */
@Service
public class PeerServiceImpl implements PeerService {
    @Resource
    private PeerMapper peerMapper;

    @Override
    public Peer getPeer(@NotNull String ip, int port, @NotNull String infoHash) {
        infoHash = infoHash.toLowerCase(Locale.ROOT);
        return peerMapper.selectOne(
                new QueryWrapper<Peer>().eq("ip", ip).eq("port", port).eq("info_hash", infoHash)
        );
    }

    @Override
    public List<Peer> getPeers(@NotNull String infoHash, int numWant) {
        infoHash = infoHash.toLowerCase(Locale.ROOT);
        Pageable top = PageRequest.of(0, numWant);
        return peerMapper.selectList(
                new QueryWrapper<Peer>()
                        .eq("info_hash", infoHash)
                        .last("LIMIT " + numWant)
                        .orderByDesc("update_at")
        );
    }

    @Override
    public Peer createOrUpdate(@NotNull Peer peer) {
        peer.setInfoHash(peer.getInfoHash().toLowerCase(Locale.ROOT));
        if(peer.getId() == null) {
            return peerMapper.insert(peer) > 0 ? peer : null;
        }
        return peerMapper.updateById(peer) > 0? peer : null;
    }

    @Override
    public void delete(@NotNull Peer peer) {
        peerMapper.deleteById(peer.getId());
    }
}
